package com.example.bmi_kotlin

import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RadioButton
import android.widget.Toast
import com.example.bmi_kotlin.databinding.ActivityMainBinding
import java.lang.Exception
import java.util.*

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        var view: View = binding.root
        setContentView(view)

        binding.btnConfirm.setOnClickListener(View.OnClickListener { // 获取输入的值
            val weightStr = binding.etWeight.text.toString()
            val heightStr = binding.etHeight.text.toString()
            // 判断是否为空
            if (TextUtils.isEmpty(weightStr) || TextUtils.isEmpty(heightStr)) {
                Toast.makeText(this, "体重或身高不能为空", Toast.LENGTH_SHORT).show()
                return@OnClickListener
            }
            // 将字符串转为float，计算bmi
            val weight = weightStr.toFloat()
            val height = heightStr.toFloat()
            val bmi = weight / Math.pow(height.toDouble(), 2.0)
            binding.tvBmi.text = String.format(Locale.CHINA, "BMI： %.2f", bmi)
            binding.tvInfo.text = "诊断：" + getInfo(bmi)
            hideKeyboard(this)
        })
    }
    private fun getInfo(bmi: Double): String? {
        // 获取RadioButton的文本
        val id = binding.rgSex.checkedRadioButtonId
        val btn = findViewById<RadioButton>(id)
        val sex = btn.text.toString()

        // 根据bmi得到信息
        var info = ""
        val isMan = sex == "男"
        info = if (bmi > 35 && isMan || bmi > 34 && !isMan) {
            "重度肥胖"
        } else if (bmi >= 30 && isMan || bmi >= 29 && !isMan) {
            "中度肥胖"
        } else if (bmi >= 27 && isMan || bmi >= 26 && !isMan) {
            "轻度肥胖"
        } else if (bmi >= 25 && isMan || bmi >= 24 && !isMan) {
            "体重超重"
        } else if (bmi >= 20 && isMan || bmi >= 19 && !isMan) {
            "体重正常"
        } else {
            "体重过轻"
        }
        return info
    }

    private fun hideKeyboard(activity: Activity) {
        val imm = activity.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        var view = activity.currentFocus
        if (view == null) {
            view = View(activity)
        }
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    fun hideKeyboardFrom(context: Context, view: View) {
        val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        //加载xml菜单资源
        val inflater = menuInflater
        inflater.inflate(R.menu.option_menu, menu)
        //动态加载菜单项
        menu.add(Menu.NONE, Menu.FIRST, 3, "清除数据").setIcon(R.drawable.ic_baseline_clear_all_24)
        setIconVisible(menu, true)
        return true
    }

    //使用反射方法显示图标
    private fun setIconVisible(menu: Menu?, flag: Boolean) {
        //判断menu是否为空
        if (menu != null) {
            try {
                val method = menu.javaClass.getDeclaredMethod(
                    "setOptionalIconsVisible",
                    java.lang.Boolean.TYPE
                )
                //强制访问该方法
                method.isAccessible = true
                //调用该方法显示icon
                method.invoke(menu, flag)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        //处理菜单项的选择
        return when (item.itemId) {
            Menu.FIRST -> {
                binding.etHeight.text.clear()
                binding.etWeight.text.clear()
                Toast.makeText(this, "清除数据", Toast.LENGTH_SHORT).show()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}